import { PGlite } from '@electric-sql/pglite';
import dotenv from 'dotenv';

// Load environment variables
dotenv.config();

async function testPGlite() {
  console.log('Testing PGlite connection...');
  
  try {
    // Create a PGlite instance
    const postgresUrl = process.env.POSTGRES_URL;
    
    if (!postgresUrl) {
      throw new Error('POSTGRES_URL environment variable is not set');
    }
    
    // Check if it's a PGlite URL
    const isPGliteUrl = postgresUrl.startsWith('pglite://');
    
    if (!isPGliteUrl) {
      console.log('Warning: POSTGRES_URL does not start with "pglite://". Current URL:', postgresUrl);
      console.log('For PGlite, it should be something like "pglite://memory"');
      
      const proceed = await question('Do you want to continue with the current URL? (y/n): ');
      if (proceed.toLowerCase() !== 'y') {
        console.log('Exiting test.');
        return;
      }
    }
    
    const options = isPGliteUrl 
      ? {} // In-memory database
      : { dataDir: postgresUrl.replace('pglite://', '') };
    
    console.log('Initializing PGlite...');
    const db = new PGlite(options);
    
    // Test with a simple query
    console.log('Running test query...');
    const result = await db.query('SELECT version();');
    
    console.log('PGlite connection successful!');
    console.log('PostgreSQL version:', result.rows[0].version);
    
    // Additional test - create and query a table
    console.log('\nCreating test table...');
    await db.query('CREATE TABLE IF NOT EXISTS pglite_test (id serial PRIMARY KEY, message text)');
    await db.query("INSERT INTO pglite_test (message) VALUES ('Hello from PGlite!')");
    
    console.log('Querying test table...');
    const tableResult = await db.query('SELECT * FROM pglite_test');
    console.log('Query result:', tableResult.rows);
    
    console.log('\n✅ PGlite is working correctly!');
  } catch (error) {
    console.error('❌ Error testing PGlite connection:', error);
    console.log('\nPlease check your configuration and try again.');
  }
}

function question(query: string): Promise<string> {
  const readline = require('readline').createInterface({
    input: process.stdin,
    output: process.stdout,
  });

  return new Promise((resolve) =>
    readline.question(query, (ans: string) => {
      readline.close();
      resolve(ans);
    })
  );
}

// Run the test
testPGlite().catch(console.error); 